<?php

namespace App\Model\Admin;

use App\Model\BaseModel;

/**
 * 系统菜单-模型
 * @author LZH
 * @since: 2021/08/12
 * Class MenuModel

 */
class MenuModel extends BaseModel
{
    // 设置数据表名
    protected $tableName = DB_PREFIX . "menu";

    /**
     * 获取缓存信息
     * @param int $id 记录ID
     * @author LZH
     * @since: 2021/08/12
     */
    public function getInfoById($id)
    {
        $info = parent::info($id);
        if ($info) {
        }
        return $info;
    }

    public function getChilds($pid)
    {
        $map = [
            'type' => [[0,1], 'IN'],
            'pid' => $pid,
            'status' => 1
        ];
        $list = $this->field(['id', 'pid', 'title', 'icon', 'path', 'component', 'target', 'permission', 'type'])
            ->where($map)->order('sort', 'asc')->all()->toArray();
        if (!empty($list)) {
            foreach ($list as &$val) {
                $val['children'] = $this->getChilds($val['id']);
            }
        }
        return $list;
    }

    /**
     * 获取权限菜单
     * @param $userId
     * @param $pid
     * @return mixed
     */
    public function getPermissionMenu($userId, $pid)
    {
        $menuList = $this->join('sc_role_menu', 'sc_role_menu.menu_id=sc_menu.id')
            ->join('sc_user_role', 'sc_user_role.role_id=sc_role_menu.role_id')
            ->where('sc_user_role.user_id', $userId)
            ->where('sc_menu.type', 0)
            ->where('sc_menu.pid', $pid)
            ->where('sc_menu.status', 1)
            ->order('sc_menu.pid', 'ASC')
            ->order('sc_menu.sort', 'ASC')
            ->field('sc_menu.*')
            ->get()->toArray();
        if (!empty($menuList)) {
            foreach ($menuList as &$val) {
                $childList = $this->getPermissionMenu($userId, $val['id']);
                if (is_array($childList) && !empty($childList)) {
                    $val['children'] = $childList;
                }
            }
        }
        return $menuList;
    }
}
